/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.openbookformat.defaultparser;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.openbookformat.core.OBFParser;
import org.openbookformat.tags.CompositeTag;
import org.openbookformat.tags.FnMarkTag;
import org.openbookformat.tags.FootnoteTag;
import org.openbookformat.tags.HeadingTag;
import org.openbookformat.tags.PagebreakTag;
import org.openbookformat.tags.ParTag;
import org.openbookformat.tags.Tag;
import org.openbookformat.tags.TagNotFoundException;
import org.openbookformat.tags.TagParsingException;
import org.openbookformat.tags.Text;
import org.openide.util.lookup.ServiceProvider;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author MUFEED
 */

@ServiceProvider(service=OBFParser.class)
public class OBFDefaultParser implements OBFParser {
    CompositeTag tags;
    
    public OBFDefaultParser() {
        tags = new CompositeTag();
    }

    @Override
    public Tag parse(String obf_text) throws TagNotFoundException {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new ByteArrayInputStream(obf_text.getBytes("windows-1256")));
          
            Element root = doc.getDocumentElement();
//            System.out.println(root.getNodeName());
           
            NodeList nodes = root.getChildNodes();
            String text = null;
            for(int i =0; i < nodes.getLength(); i++) {
                text = nodeToXML(nodes.item(i));
//                System.out.println("[" + i + "]" +nodes.item(i).getNodeName());
//                System.out.print(text);             
                if(text.trim().length() != 0)
                    tags.addTag(toTag(nodes.item(i).getNodeName(), text));
            }
            
            System.out.println("\n\n\n--------------------------------");
            for(int i = 0; i < tags.size(); i++)
                System.out.println(tags.getTag(i));
            
        } catch (TagParsingException ex) {
            Logger.getLogger(OBFDefaultParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(OBFDefaultParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(OBFDefaultParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(OBFDefaultParser.class.getName()).log(Level.SEVERE, null, ex);
        }
        return tags;
    }
   
    private String nodeToXML(Node node) {       
        String xml = null;
        if(node.getNodeName().equals("#text")) {
            return node.getTextContent();
        }
       
        xml = "<" + node.getNodeName();
        NamedNodeMap attr = node.getAttributes();
        if(attr.getLength() != 0) {
            for(int i = 0; i < attr.getLength(); i++)
                xml += " " + attr.item(i).toString().replace("\"", "'");           
        }
       
        NodeList nodes = node.getChildNodes();
        if(nodes.getLength() == 0) {
            xml += " />";
        } else {
            xml += ">";
            for(int i =0; i < nodes.getLength(); i++)
                xml += nodeToXML(nodes.item(i));
            xml += "</" + node.getNodeName() + ">";
        }
        return xml;
    }
    
    private Tag toTag(String node, String text) throws TagParsingException {    
        if(node.equals("#text")) {
            //System.out.println("###" + text + "###" + text.length());
            //System.out.println(text.lastIndexOf("\n")== -1? text.length():text.lastIndexOf("\n"));
            System.out.println("Text:" + text.substring(1, 
                    text.charAt(text.length() -1) == '\n'? text.length() -1:text.length()));
            return new Text(text.substring(1, 
                    text.charAt(text.length() -1) == '\n'? text.length() -1:text.length()));
        } else if(node.equals("par")) {
            return new ParTag();
        } else if(node.equals("pagebreak")) {
            return PagebreakTag.parse(text);
        } else if(node.equals("footnote")) {
            return FootnoteTag.parse(text);
        } else if(node.equals("heading")) {
            return HeadingTag.parse(text);
        } else if(node.equals("fn_mark")) {
            return FnMarkTag.parse(text);
        }
        return null;
    }
}
